import { App, Button, Flex, Form, Input, Modal, Select, Space, Table, Tag } from "antd";
import { useContext, useEffect, useState } from "react";
import user_api, { USER_ROLE } from "../api/users";
import { useForm } from "antd/es/form/Form";
import Search from "antd/es/input/Search";
import { Global } from "../main";

export function Acount() {
    const [searchLoading, setSearchLoading] = useState(false)
    const [userPage, setUserPage] = useState({ total: 0, content: [] })
    const [userReq, setUserReq] = useState({ keyword: '', page: 1, size: 15 })
    const [updateUserModalOpen, setUpdateUserModalOpen] = useState(false)
    const [createUserModalOpen, setCreateUserModalOpen] = useState(false)
    const [createUserForm] = useForm();
    const [updateUserForm] = useForm();
    const { message, modal } = App.useApp();
    const [currentUser, setCurrentUser] = useState(null);
    const { role } = useContext(Global)

    const columns = [
        {
            title: '用户名',
            dataIndex: 'username',
            key: 'username',
        },
        {
            title: '权限',
            key: 'role',
            render: (_, row) => {
                if (row.role === USER_ROLE.MANAGER) {
                    return (<Tag>管理</Tag>)
                } else {
                    return (<Tag>查询</Tag>)
                }
            }
        },
        {
            title: '操作',
            key: 'action',
            fixed: 'right',
            width: 150,
            render: (_, row) => (<Space size={'middle'}>
                <Button disabled={role === USER_ROLE.READONLY} type="link" onClick={() => {
                    updateUserForm.setFieldsValue(row);
                    setCurrentUser(row);
                    setUpdateUserModalOpen(true)
                }}>编辑</Button>
                <Button disabled={role === USER_ROLE.READONLY} type="link" danger onClick={() => modal.confirm({
                    title: "删除用户",
                    content: `确认要删除用户：${row.username}吗？`,
                    onOk: () => {
                        user_api.deleteUser(row.id).then(() => {
                            reFreshUser();
                        }).catch(e => message.error(e))
                    },
                    okText: '确定',
                    cancelText: '取消'
                })}>删除</Button>
            </Space>)
        },
    ];
    const reFreshUser = (ur) => {
        let request = userReq;
        if (!!ur) {
            request = ur;
        }
        user_api.pageUser(request).then(data => {
            setUserPage({...data, content: data.content.map(it=>({...it, key: it.id}))})
            setSearchLoading(false)
        }).catch(e => message.error(e))
    }

    useEffect(() => {
        reFreshUser()
    }, []);
    return <>
        <Space style={{ margin: '10px' }}>
            <Search size="large" placeholder="输入关键字进行搜素" style={{ maxWidth: '30vw' }} loading={searchLoading} onSearch={(value) => {
                setSearchLoading(true)
                setUserReq({ ...userReq, keyword: value })
                reFreshUser({ ...userReq, keyword: value })
            }}></Search>
            <Button size="large" type="primary" onClick={() => {
                setCurrentUser(null)
                createUserForm.setFieldsValue(null)
                createUserForm.resetFields()
                setCreateUserModalOpen(true)
            }} disabled={role === USER_ROLE.READONLY}>创建</Button>
        </Space>
        <Table size="small" pagination={{
            position: ["bottomLeft"],
            pageSizeOptions: [userReq.size],
            total: userPage.total,
            current: userReq.page,
            pageSize: userReq.size,
            onChange: (page, pageSize) => {
                console.log(page, pageSize)
                setUserReq({ ...userReq, page: page, size: pageSize });
                reFreshUser({ ...userReq, page: page, size: pageSize })

            }
        }} dataSource={userPage.content} columns={columns}></Table>
        <Modal title="编辑账户" maskClosable={false} okText="确定" cancelText="取消" onOk={() => {

            updateUserForm.validateFields().then(data => {
                user_api.updateUser(data).then(() => {
                    reFreshUser();
                    setUpdateUserModalOpen(false)
                }).catch(e => message.error(e.response.data))
            });

        }} onCancel={() => setUpdateUserModalOpen(false)} open={updateUserModalOpen}>
            <Form labelCol={{ span: 6 }} value={currentUser} wrapperCol={{ span: 18 }} form={updateUserForm} initialValues={currentUser}>
                <Form.Item label="索引" name={"id"} hidden>
                    <Input />
                </Form.Item>
                <Form.Item label="用户名" name={"username"} rules={[{
                    required: true,
                    message: '请输入用户名'
                }]}>
                    <Input></Input>
                </Form.Item>
                <Form.Item label="密码" name={"password"} rules={[{
                    required: true,
                    message: '请输入密码'
                }]}>
                    <Input.Password></Input.Password>
                </Form.Item>
                <Form.Item label="权限" name={"role"} rules={[{
                    required: true,
                    message: '请指定用户权限'
                }]}>
                    <Select>
                        <Select.Option value={1}>管理</Select.Option>
                        <Select.Option value={0}>查询</Select.Option>
                    </Select>
                </Form.Item>
            </Form>
        </Modal>
        <Modal title="新建账户" maskClosable={false} okText="确定" cancelText="取消" onOk={() => {
            createUserForm.validateFields().then(data => {
                user_api.createUser(data).then(() => {
                    reFreshUser();
                    setCreateUserModalOpen(false)
                }).catch(e => message.error(e.response.data))
            });

        }} onCancel={() => setCreateUserModalOpen(false)} open={createUserModalOpen}>
            <Form labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} form={createUserForm} initialValues={currentUser}>
                <Form.Item label="用户名" name={"username"} rules={[{
                    required: true,
                    message: '请输入用户名'
                }]}>
                    <Input></Input>
                </Form.Item>
                <Form.Item label="密码" name={"password"} rules={[{
                    required: true,
                    message: '请输入密码'
                }]}>
                    <Input.Password></Input.Password>
                </Form.Item>
                <Form.Item label="权限" name={"role"} rules={[{
                    required: true,
                    message: '请指定用户权限'
                }]}>
                    <Select>
                        <Select.Option value={1}>管理</Select.Option>
                        <Select.Option value={0}>查询</Select.Option>
                    </Select>
                </Form.Item>
            </Form>
        </Modal>
    </>
}